var config = {

    logoMargin: 10,
    logoBorderWidth: 3,
    logoBorderRadius: 10,
    logoVerticalOffset: 50
};

var info = {

    documentWidth: undefined,
    documentHeight: undefined,
    logoPosition: { },
    introTextPosition: { },
    loginTextPosition: { },
    instructionTextPosition: { },
    emailContainerPosition: { },
    produceListPosition: { },
    paymentOptionsPosition: { },
    columnWidth: undefined,
    addressDiv: undefined,
    customer: { },
    addressContainer: undefined,
    deliveryOptionsContainer: undefined,
    deliveryOptionsPosition: { },
    deliveryOptionsContainerWidth: undefined,
    rowToBeDeleted: undefined,
    selectedAddress: undefined,
    loginButtonPosition: {},
    footer: undefined,
    checkoutButtonPosition: { },
    minimumTotal: 25,
    currentTotal: 0
};

function setDocumentInfo() {
    
    info.documentWidth = $( document ).width();
    info.documentHeight = $( document ).height();

    info.columnWidth = Math.floor( ( info.documentWidth * .80 ) / 6 );
}

function makeLogoPretty() {

    $('#logoImage')
        .css( { 'float': 'left', 
                'background-image': 'url(images/logo.png)',
                'height': '209px',
                'width': '540px',
                'margin': [ config.logoMargin, 'px' ].join('') } );
    
    $('#logoBorder3').css( { 'float': 'left',
                             'margin': [ config.logoMargin, 'px' ].join(''),
                             '-moz-border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border': [ config.logoBorderWidth, 'px solid #EEDFCC' ].join('') } );
    
    $('#logoBorder2').css( { 'float': 'left',
                             'margin': [ config.logoMargin, 'px' ].join(''),
                             '-moz-border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border': [ config.logoBorderWidth, 'px solid #74C365' ].join('') } );
    
    $('#logoBorder1').css( { 'float': 'left',
                             '-moz-border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border': [ config.logoBorderWidth, 'px solid #87CEEB' ].join('') } );

    var logoContainer = $( '#logoContainer' ).css( { 'position': 'absolute' } );

    var logoContainerWidth = logoContainer.outerWidth( true );

    logoContainer.css( { 'top': config.logoVerticalOffset,
                         'left': ( ( info.documentWidth - logoContainerWidth ) / 2 ) } );

    storeObjPosition( logoContainer, info.logoPosition );
}

function makeLoginPretty() {

    var loginText = $( '#loginText' )
        .css( { 'position': 'absolute',
                'margin': '0px 10px' } );
    
    var loginTextWidth = loginText.outerWidth( true );

    loginText.css( {
        'text-align': 'center',
        'left': ( ( info.documentWidth - loginTextWidth ) / 2 ),
        'top': info.introTextPosition.myBottom + 35 } );
 
    storeObjPosition( loginText, info.loginTextPosition );

    var emailContainer = $('#emailContainer')
        .css( { 'position': 'absolute' } );

    $('#emailAddress').css( {
        'padding': '5px',
        'text-align': 'center',
        'border-radius': [ config.logoBorderRadius, 'px' ].join('') } ).attr( {
        'size': '75' } );
    
    var emailContainerWidth = emailContainer.outerWidth( true );

    emailContainer.css( {
        'left': ( ( info.documentWidth - emailContainerWidth ) / 2 ),
        'top': info.loginTextPosition.myBottom + 10 } );
    
    storeObjPosition( emailContainer, info.emailContainerPosition );

    info.loginButton = $('#loginButton').css( {
        'padding': '5px',
        'border': '1px solid #74C365',
        'background-color': '#87CEEB',
        'border-radius': [ config.logoBorderRadius, 'px' ].join(''),
        'position': 'absolute' } )
      .hover( setMouseToPointer, setMouseToDefault )
      .hover( underlineText, unUnderlineText )
      .bind( 'mousedown', { }, handleButtonClick )
      .bind( 'mouseup', { }, handleButtonUnClick )
      .bind( 'click', { }, handleLoginAttempt );

    var loginButtonWidth = info.loginButton.outerWidth( true );

    info.loginButton.css( {
        'left': ( ( info.documentWidth - loginButtonWidth ) / 2 ),
        'top': info.emailContainerPosition.myBottom + 10 } );
    
    storeObjPosition( info.loginButton, info.loginButtonPosition );

    $( document ).bind( 'keydown', checkForLoginWithEnter );

    info.footer = makeEl( 'div' ).css( {
        'position': 'absolute',
        'background-color': 'white',
        top: info.loginButtonPosition.myBottom + 10 } )
            .height( 30 )
            .width( 30 );

    $('body').append( info.footer );
}

function checkForLoginWithEnter( e ) {

    if( e.keyCode == 13 ) {
        
        $( document ).unbind( 'keydown', checkForLoginWithEnter );
        handleLoginAttempt();
    }
}
        
function showNoLogin() {

    $('#modalBoxTitle').text( 'Not accepting orders' );
    $('#modalBoxForm').append( makeEl('div').attr( { 'class': 'modalText' } ).text( 'We are not taking orders at this time.' ) );

    info.modalWait = true;
    
    $('#modalBoxContainer').show( 'slow', alignModalBox );

}

function handleLoginAttempt() {

    info.loginButton.unbind('click');

    showNoLogin();
    return;

    var emailAddress = $.trim( $('#emailAddress').val() ).toLowerCase();

    if( emailAddress ) {

        var url = [ 'http://patchworkgardens.net/cgi-bin/login.py?email=',
                    encodeURIComponent( emailAddress ) ].join('');

        $.ajax( { url: url,
                  type: 'GET',
                  success: handleLoginResponse } );

        showModalWait();

        info.emailAddress = emailAddress;
    }
}

function showModalWait() {

    $('#modalBoxTitle').text( '' );
    $('#modalBoxForm').append( makeEl('div').attr( { 'class': 'modalText' } ).text( 'Please Wait.' ) );

    info.modalWait = true;
    
    $('#modalBoxContainer').show( 'slow', alignModalBox );
}

function handleLoginResponse( response ) {
   
    info.customer = eval( '(' + response + ')' );

    if( info.customer.deliveryInfo ) {
        
        $('#loginText').hide('slow');
        $('#emailContainer').hide('slow');
        $('#loginButton').hide( 'slow', afterLogin );
        

    } else {
        
        closeModalBox();

        $('#modalBoxTitle').text( 'Login Error' );
        $('#modalBoxForm').append( makeEl('div').attr( { 'class': 'modalText' } ).text( 'We were unable to find the given email address in our database.  Please make sure it is entered correctly.  If it still does not work, please email or give us a call.' ) );
        
        $('#modalBoxContainer').show( 'fast', alignModalBox );
  
        info.loginButton.bind( 'click', { }, handleLoginAttempt );
        $( document ).bind( 'keydown', checkForLoginWithEnter );
    }
}

function afterLogin() {

    makeInstructionTextPretty();
   
    makeProduceListPretty();

    $('#paymentOptionsTitle').css( { 'font-size': '30px', 'text-align': 'center', color: '#87CEEB', 'margin': '5px' } );
    $('#deliveryOptionsTitle').css( { 'font-size': '30px', 'text-align': 'center', color: '#87CEEB', 'margin': '5px' } );

    $.ajax( { url: 'http://patchworkgardens.net/cgi-bin/getProduce.py?ts=' + new Date().getTime(),
              type: 'GET',
              success: handleProduceResponse } );

    $('#produceListTotalLabel')
        .width( 5 * info.columnWidth + 20 )
        .css( { 'font-weight': 'bold', 'font-size': '20px', 'margin': '5px 0px', 'text-align': 'right', float: 'left' } );

    $('#produceListTotalValue')
        .css( { 'font-weight': 'bold', 'float': 'left', 'text-align': 'center', 'margin': '5px 2px' } )
        .width( info.columnWidth );
}

function makeIntroTextPretty() {

    var introText = $( '#introductionText' )
        .css( { 'position': 'absolute',
                'margin': '0px 10px' } );
    
    var introTextWidth = introText.outerWidth( true );

    introText.css( {
        'text-align': 'center',
        'left': ( ( info.documentWidth - introTextWidth ) / 2 ),
        'top': info.logoPosition.myBottom + 25 } );
 
    storeObjPosition( introText, info.introTextPosition );
}

function makeInstructionTextPretty() {

    var instructionText = $( '#instructionText' )
        .css( { 'position': 'absolute',
                'margin': '0px 10px' } ).show();
    
    var instructionTextWidth = instructionText.outerWidth( true );

    instructionText.css( {
        'text-align': 'center',
        'left': ( ( info.documentWidth - instructionTextWidth ) / 2 ),
        'top': info.introTextPosition.myBottom + 25 } );
    
    storeObjPosition( instructionText, info.instructionTextPosition );
}

function makeProduceListPretty() {

    $('.produceListColumnTitle')
        .width( info.columnWidth )
        .css( { 'float': 'left',
                'text-align': 'center',
                'font-size': '20px',
                'font-weight': 'bold',
                'margin': '5px 2px' } );


    $('#produceListTitle').css( { 'font-size': '30px', 'text-align': 'center', color: '#87CEEB', 'margin': '5px' } );

    var produceListContainer =
        $( '#produceListContainer' )
            .css( { 'position': 'absolute',
                    'background-color': '#EEDFCC' } ).show();
    
    var produceListContainerWidth = produceListContainer.outerWidth( true );

    produceListContainer.css( {
        'left': ( ( info.documentWidth - produceListContainerWidth ) / 2 ),
        'top': info.instructionTextPosition.myBottom + 50,
        '-moz-border-radius': [ config.logoBorderRadius, 'px' ].join(''),
        'border-radius': [ config.logoBorderRadius, 'px' ].join('') } );
}

function hideStuffBeforeLogin() {

    $('#instructionText').hide();
    $('#produceListContainer').hide();
    $('#paymentOptionsContainer').hide();
    $('#deliveryOptionsContainer').hide();
}

function onPageLoad() {

    setDocumentInfo();

    hideStuffBeforeLogin();

    makeLogoPretty();

    makeIntroTextPretty();

    makeLoginPretty();
    
    initializeModalBox();
}

function handleProduceResponse( response ) {
    
    closeModalBox();

    var produceInfo = eval( '(' + response + ')' );

    var produceList = $('#produceList');

    for( var i = 0, ii = produceInfo.length; i < ii; i++ ) {

        produceList.append(
            makeEl('div').attr( { 'produceId': produceInfo[i].id, 'id': [ 'produce', produceInfo[i].id ].join('') } ).css( { 'text-align': 'center' } ).append(
                makeEl('div').text( produceInfo[i].name )
                              .width( info.columnWidth )
                              .css( { 'float': 'left', 'color': '#74C365', 'text-decoration': 'underline', 'margin': '5px 2px' } )
                              .hover( setMouseToPointer, setMouseToDefault )
                              .bind( 'click', { name: produceInfo[i].name, description: produceInfo[i].description }, showProduceDescription ),
                makeEl('div').css( { 'float': 'left', 'margin': '5px 2px' } ).text( produceInfo[i].unit ).width( info.columnWidth ),
                makeEl('div').attr( { 'class': 'unitPrice' } )
                             .css( { 'float': 'left', 'margin': '5px 2px' } ).text( [ '$', produceInfo[i].unitPrice.toFixed(2) ].join('') ).width( info.columnWidth ),
                makeEl('div').css( { 'float': 'left', 'margin': '5px 2px'  } ).width( info.columnWidth ).append(
                    makeEl('input').attr( { 'class': 'quantity', 'size': 3 } )
                                   .css( { 'text-align': 'center', 
                                           'border-radius': [ config.logoBorderRadius, 'px' ].join('') } )
                                   .bind( 'keydown', { id: produceInfo[i].id }, handleQuantityKeyPress ) 
                                   .val( 0 ) ),
                makeEl('div').attr( { 'class': 'available', 'originalValue': produceInfo[i].unitsRemaining } )
                             .css( { 'float': 'left', 'margin': '5px 2px' } ).text( produceInfo[i].unitsRemaining ).width( info.columnWidth ),
                makeEl('div').attr( { 'class': 'price' } ).css( { 'float': 'left', 'margin': '5px 2px'  } ).width( info.columnWidth ).text( '$0.00' ),
                makeEl('div').attr( { 'class': 'clear' } ) ) );
    }

    storeObjPosition( $('#produceListContainer'), info.produceListPosition );

    positionPaymentOptions();
    positionDeliveryOptions();
    addCheckoutButton();
}

function editAddress() {

    $(this).unbind('click');

    info.addressDiv = $( $(this).prev() );

    $('#modalBoxTitle').text( 'Edit Address' );
   
    $('#modalBoxForm').append(
        makeEl( 'div' ).append(     
            makeModalTextInput( { name: 'editAddress',
                                 value: info.addressDiv.text(),
                                 text: 'Address' } ) ),
            makeModalActionRow( { submitText: 'Edit', onClick: $.proxy( actuallyEditAddress, this ) } ) );
    
    $('#modalBoxContainer').show( 'slow', alignModalBox );
}

function actuallyEditAddress() {

    var editedAddress = $( $('#modalBoxForm input[type="text"]')[0] ).val();

    if( editedAddress != info.addressDiv.text() ) {

        var url = [ 'http://patchworkgardens.net/cgi-bin/editAddress.py?address=',
                        encodeURIComponent( editedAddress ),
                        '&id=', encodeURIComponent( info.addressDiv.attr('addressId') ) ].join('');

        $.ajax( { url: url,
                  type: 'GET',
                  success: $.proxy( handleEditAddressResponse, this ) } );

        info.editedAddress = $( $('#modalBoxForm input[type="text"]')[0] ).val();

        closeModalBox();

        showModalWait();

    } else {
    
        closeModalBox();

        $( this ).bind( 'click', { }, editAddress );
    }
}

function handleEditAddressResponse() {

    info.addressDiv.text( info.editedAddress );

    closeModalBox();

    $( this ).bind( 'click', { }, editAddress );
}

function deleteAddress( p ) {

    $( this ).unbind( 'click' );

    addressId = p.data.addressId;

    info.rowToBeDeleted = $( $( $( [ 'div[addressId="', addressId, '"]' ].join('') )[0] ).parent() )

    var url = [ 'http://patchworkgardens.net/cgi-bin/deleteAddress.py?addressId=',
                    encodeURIComponent( addressId ) ].join('');

    $.ajax( { url: url,
              type: 'GET',
              success: $.proxy( handleDeleteAddressResponse, this ) } );

    showModalWait();
}

function handleDeleteAddressResponse() {
                               
    closeModalBox();

    var removeElement = function() { 
        info.rowToBeDeleted.next().remove();
        info.rowToBeDeleted.remove();
        info.rowToBeDeleted = undefined;
    }

    var callback = function() { removeElement(); resizeAddressBox(); }

    if( $( info.selectedAddress ).get(0) == info.rowToBeDeleted.children()[0] ) {

        callback = function() { removeElement(); resizeAddressBox(); updateSelectedAddress(); }
    }
    
    info.rowToBeDeleted.hide( 'slow', callback );
}

function updateSelectedAddress() {

    info.selectedAddress =
        $( $( info.addressContainer.children()[0] ).children()[0] )
            .css( { 'background-color': '#74C365' } )
            .attr( { 'selected': 'true' } );
}

function resizeAddressBox() {

    $( info.newAddress.parent() ).height(
            info.addressHeader.outerHeight( true ) +
            info.addressContainer.outerHeight( true ) +
            info.newAddress.outerHeight( true ) + 15 );
}

function addNewAddress() {

    var newAddress = $.trim( $( $('.addNewAddress')[0] ).val() );

    if( newAddress.length ) {

        info.addNewAddressButton.unbind('click');

        var url = [ 'http://patchworkgardens.net/cgi-bin/addNewAddress.py?address=',
                        encodeURIComponent( newAddress ),
                        '&customerId=',
                        encodeURIComponent( info.customer.deliveryInfo.customerId ) ].join('');

        $.ajax( { url: url,
                  type: 'GET',
                  success: handleAddNewAddressResponse } );
            
        showModalWait();
    }
}

function handleAddNewAddressResponse( response ) {

    closeModalBox();

    var responseObj = eval( '(' + response + ')' );
    
    var row = makeAddressRow( { addressId: responseObj.addressId,
                                address: $( $('.addNewAddress')[0] ).val() } );

    $( $('.addNewAddress')[0] ).val('')
            
    info.addressContainer.append( row, makeEl('div').css({'clear':'both'} ) );
    
    var rowWidth = row.outerWidth( true );
    
    row.css( { 'left': ( info.deliveryOptionsContainerWidth - rowWidth ) / 2 } );

    if( ! info.selectedAddress.length ) {
        
        info.selectedAddress = $( row.children()[0] ).css( { 'background-color': '#74C365' } );
    }

    $( info.newAddress.parent() ).height(
            info.addressHeader.outerHeight( true ) +
            info.addressContainer.outerHeight( true ) +
            info.newAddress.outerHeight( true ) + 15 );
        
    info.addNewAddressButton.bind( 'click', { }, addNewAddress );
}

function selectAddress() {

    if( this == info.selectedAddress.get(0) ) { return; }

    info.selectedAddress.css( { 'background-color': '' } );
    info.selectedAddress = $( this ).css( { 'background-color': '#74C365' } );
}

function highlightAddress() { $(this).css( { 'background-color': 'lightGreen' } ); }

function unHighlightAddress() {
    
    if( this == info.selectedAddress.get(0) ) { 

        $(this).css( { 'background-color': '#74C365' } );

    } else {

        $(this).css( { 'background-color': '' } );
    }
}

function makeAddressRow( p ) {

    return makeEl( 'div' ).css( { 'position': 'relative', 'float': 'left', 'padding': '5px',
                                  'border-radius': [ config.logoBorderRadius, 'px' ].join('') } ).append(
                makeEl( 'div' ).css( { 'padding': '5px',
                                       'border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                                       'float': 'left' } )
                               .attr( { 'addressId': p.addressId } )
                               .hover( setMouseToPointer, setMouseToDefault )
                               .hover( highlightAddress, unHighlightAddress )
                               .bind( 'click', { }, selectAddress )
                               .text( p.address ),
                makeEl( 'div' ).css( { 'padding': '5px 5px', 'color': 'red', 'float': 'left' } )
                               .text( 'Edit' )
                               .hover( setMouseToPointer, setMouseToDefault )
                               .bind( 'click', { }, editAddress ),
                makeEl( 'div' ).css( { 'padding': '5px 5px', 'color': 'red', 'float': 'left' } )
                               .text( 'Delete' )
                               .hover( setMouseToPointer, setMouseToDefault )
                               .bind( 'click', { addressId: p.addressId }, deleteAddress ),
                makeEl( 'div' ).css( { 'clear': 'both' } ) );
}

function positionDeliveryOptions() {

    info.deliveryOptionsContainer =
        $( '#deliveryOptionsContainer' )
            .css( { 'position': 'absolute',
                    'margin': '10px',
                    'background-color': '#EEDFCC' } ).show();

    $('#deliveryOptionsText')
        .css( {
            'padding': '10px',
            'text-align': 'center'
            } )
        .text( [
            'Our records state you are in the ',
            info.customer.deliveryInfo.locationName,
            ' area.  If this is not the case, please let us know.  Our next delivery to the area is scheduled for ',
            info.customer.deliveryInfo.nextDelivery ].join('') );

    /*
    info.deliveryOptionsContainerWidth = info.deliveryOptionsContainer.outerWidth( true );

    info.deliveryOptionsContainer.css( {
        'left': ( ( info.documentWidth - info.deliveryOptionsContainerWidth ) / 2 ),
        'top': info.paymentOptionsPosition.myBottom + 25,
        '-moz-border-radius': [ config.logoBorderRadius, 'px' ].join(''),
        'border-radius': [ config.logoBorderRadius, 'px' ].join('') } ); */

    info.addressContainer = makeEl('div').css( { 'position': 'relative' } );

    for( var i = 0, ii = info.customer.addresses.length; i < ii; i++ ) {

        var row = makeAddressRow( { addressId: info.customer.addresses[i].id,
                                    address: info.customer.addresses[ i ].address } );

        info.addressContainer.append( row, makeEl('div').css({'clear':'both'} ) );
    }

    info.addNewAddressButton =
        makeEl( 'div' ).css( { 'float': 'right', 'padding': '5px',
                               'border': '1px solid #74C365',
                               'margin-bottom': '-3px',
                               'background-color': '#87CEEB',
                               'border-radius': [ config.logoBorderRadius, 'px' ].join('') } )
                       .text('Add')
                       .bind( 'mousedown', { }, handleButtonClick )
                       .bind( 'mouseup', { }, handleButtonUnClick )
                       .hover( setMouseToPointer, setMouseToDefault )
                       .hover( underlineText, unUnderlineText )
                       .bind( 'click', { }, addNewAddress );

    info.newAddress =
        makeEl( 'div' ).css( { 'position': 'relative', 'float': 'left', 'padding-top': '15px' } ).append(
            makeEl( 'div' ).css( { 'float': 'left', 'padding': '5px', 'margin-top': '3px' } ).text('Add new address here : '),
            makeEl( 'input' ).css ( { 'padding': '5px', 'border-radius': [ config.logoBorderRadius, 'px' ].join('') } )
                             .attr( { 'class': 'addNewAddress', 'size': 75, 'type': 'text' } ),
            info.addNewAddressButton,
            makeEl( 'div' ).css( { 'clear': 'both' } ) );

    info.addressHeader = makeEl( 'div' ).css( { 'padding': '10px 5px 5px 5px', 'text-align': 'center' } )
                               .text( 'Listed below are the address(es) we have associated with you.  We will deliver to the address highlighted in green.  If you have multiple addresses listed, you may need to click on an address to select it for delivery. ' );

    info.deliveryOptionsContainer.append(
        makeEl( 'div' ).append(
            makeEl( 'div' ).css( { 'border': '1px black solid',
                                   'margin': '5px 20px',
                                   'border-radius': [ config.logoBorderRadius, 'px' ].join('') } ).append(
                info.addressHeader,
                info.addressContainer,
                info.newAddress ) ) );

    info.deliveryOptionsContainerWidth = info.deliveryOptionsContainer.outerWidth( true );

    info.deliveryOptionsContainer.css( {
        'left': ( ( info.documentWidth - info.deliveryOptionsContainerWidth ) / 2 ),
        'top': info.paymentOptionsPosition.myBottom + 25,
        '-moz-border-radius': [ config.logoBorderRadius, 'px' ].join(''),
        'border-radius': [ config.logoBorderRadius, 'px' ].join('') } );

    info.addressContainer.children().each( function( i, el ) {

        var row = $(el);

        var rowWidth = row.outerWidth( true );

        row.css( { 'left': ( info.deliveryOptionsContainerWidth - rowWidth ) / 2 } );
    } );

    var newAddressWidth = info.newAddress.outerWidth( true );

    info.newAddress.css( { 'left': ( info.deliveryOptionsContainerWidth - newAddressWidth ) / 2 } );

    $( info.newAddress.parent() ).height(
        info.addressHeader.outerHeight( true ) +
        info.addressContainer.outerHeight( true ) +
        info.newAddress.outerHeight( true ) + 15 );

    info.selectedAddress =
        $( $( info.addressContainer.children()[0] ).children()[0] )
            .css( { 'background-color': '#74C365' } )
            .attr( { 'selected': 'true' } );

    storeObjPosition( info.deliveryOptionsContainer, info.deliveryOptionsPosition );
}

function positionPaymentOptions() {

    var paymentOptionsContainer =
        $( '#paymentOptionsContainer' )
            .css( { 'position': 'absolute',
                    'margin': '10px',
                    'background-color': '#EEDFCC' } ).show();
    
    var paymentOptionsContainerWidth = paymentOptionsContainer.outerWidth( true );

    paymentOptionsContainer.css( {
        'left': ( ( info.documentWidth - paymentOptionsContainerWidth ) / 2 ),
        'top': info.produceListPosition.myBottom + 25,
        '-moz-border-radius': [ config.logoBorderRadius, 'px' ].join(''),
        'border-radius': [ config.logoBorderRadius, 'px' ].join('') } );

    $('#paymentOptions').css( { 'padding': '10px' } );
    $('#paymentOptions input[type="radio"]').css( { 'padding': '10px' } );
    
    storeObjPosition( paymentOptionsContainer, info.paymentOptionsPosition );
}

function handleQuantityKeyPress( e ) {

   var quantityEl = $(this);
   var key = e.keyCode || e.which;

   stringKey = String.fromCharCode( key );

   var regex = /[0-9]/;

   if( ! regex.test( stringKey ) ) {

       if( e.keyCode == 8 || e.keyCode == 46 ) {
       
           setTimeout( function() { updatePrice( e.data.id, quantityEl ); }, 200 );
      
       } else if( e.keyCode == 37 || e.keyCode == 39 ) {

           return;

       } else {

           e.returnValue = false;

           if( e.preventDefault ) { e.preventDefault(); }
       }

   } else {

       setTimeout( function() { updatePrice( e.data.id, quantityEl );  }, 200 );
   }
}

function updatePrice( id, quantityEl ) {

    var unitPriceSelector = [ '#produce', id, ' div.unitPrice' ].join('')
    var priceSelector = [ '#produce', id, ' div.price' ].join('')
    var unitsAvailableSelector = [ '#produce', id, ' div.available' ].join('')

    var unitsAvailableEl = $( $( unitsAvailableSelector )[0] );

    var quantityAmount;

    if( quantityEl.val() == '' ) { quantityAmount = 0; }
    else { quantityAmount = parseInt( quantityEl.val() ); }

    if( quantityAmount > unitsAvailableEl.attr('originalValue') ) {

        quantityEl.val( unitsAvailableEl.attr('originalValue') );
        quantityAmount = parseInt( unitsAvailableEl.attr('originalValue') );
    }
    
    unitsAvailableEl.text( parseInt( unitsAvailableEl.attr('originalValue') ) - quantityAmount );

    var unitPrice = parseFloat( $( $( unitPriceSelector )[0] ).text().substr(1) );

    var amount = ( unitPrice * quantityEl.val() ).toFixed(2);

    $( $( priceSelector )[0] ).text( [ '$', amount ].join('') );

    var totalAmount = 0; 

    $('div.price').each( function( i ) {
        totalAmount += parseFloat( $( this ).text().substr(1) );
    } );

    info.currentTotal = totalAmount.toFixed(2);

    $( '#produceListTotalValue' ).text( [ '$', totalAmount.toFixed(2) ].join('') );
}

function showProduceDescription( e ) {

    $( this ).unbind( 'click' );

    $('#modalBoxTitle').text( e.data.name );
    $('#modalBoxForm').append( makeEl('div').attr( { 'class': 'modalText' } ).text( e.data.description ) );
    
    $('#modalBoxContainer').show( 'slow', alignModalBox );

    var buttonElement = $(this);
    setTimeout( function() { buttonElement.bind( 'click', e.data, showProduceDescription ); }, 1000 );
}

function addCheckoutButton() {

    storeObjPosition( info.deliveryOptionsContainer, info.deliveryOptionsPosition );

    info.checkoutButton =
        makeEl( 'div' ).css( {
            'padding': '5px',
            'border': '1px solid #74C365',
            'background-color': '#87CEEB',
            'border-radius': [ config.logoBorderRadius, 'px' ].join(''),
            'position': 'relative' } )
          .hover( setMouseToPointer, setMouseToDefault )
          .hover( underlineText, unUnderlineText )
          .bind( 'mousedown', { }, handleButtonClick )
          .bind( 'mouseup', { }, handleButtonUnClick )
          .width( 150 )
          .text('Checkout')
          .bind( 'click', { }, handleCheckoutClick );

    info.checkoutContainer = makeEl( 'div' ).css( { 'position': 'absolute', 'text-align': 'center', 'top': info.deliveryOptionsPosition.myBottom + 25 } );

    $( 'body' ).append(
        info.checkoutContainer.append( 
            makeEl( 'div' ).css( { 'padding': '20px' } ).text( "Click the 'Checkout' button below to complete your order.  Upon doing so, you should receive an email as a record of your order.  Thanks!" ),
            info.checkoutButton
             ) );

    var checkoutContainerWidth = info.checkoutContainer.outerWidth( true );

    info.checkoutContainer.css( { 'left': ( ( info.documentWidth - checkoutContainerWidth ) / 2 ) } );
    info.checkoutButton.css( { 'left': ( ( checkoutContainerWidth - info.checkoutButton.outerWidth( true ) ) / 2 ) } );

    storeObjPosition( info.checkoutButton, info.checkoutButtonPosition );

    info.footer.css( { 'top': info.checkoutButtonPosition.myBottom + 25 } );
}

function handleCheckoutClick() {

    info.checkoutButton.unbind('click');

    if( info.minimumTotal > info.currentTotal ) {

        $('#modalBoxTitle').text( 'Minimum Total For Delivery' );

        $('#modalBoxForm').append(
            makeEl('div').attr( { 'class': 'modalText' } )
                         .text( [ 'Unfortunately, we require an order of at least $',
                                  info.minimumTotal.toFixed(2),
                                  ' for delivery.'].join('') ) );
        
        $('#modalBoxContainer').show( 'fast', alignModalBox );
       
        info.checkoutButton.bind( 'click', { }, handleCheckoutClick );

        return;
    }

    if( ! info.selectedAddress.length ) {
        
        $('#modalBoxTitle').text( 'Delivery Address' );
        $('#modalBoxForm').append(
            makeEl('div').attr( { 'class': 'modalText' } )
                         .text( 'Please add an address for us to deliver to.' ) );
        
        $('#modalBoxContainer').show( 'fast', alignModalBox );
        
        info.checkoutButton.bind( 'click', { }, handleCheckoutClick );

        return;
    }
    
    $.ajax( { url: 'http://patchworkgardens.net/cgi-bin/getUnitsAvailable.py',
              type: 'GET',
              success: checkUnitsAvailable } );

    showModalWait();
}

function checkUnitsAvailable( response ) {

    var produceInfo = eval( '(' + response + ')' );

    var unableToFulfill = false;

    for( var i = 0, ii = produceInfo.length; i < ii; i++ ) {

        var quantitySelector = [ 'div[produceId="', produceInfo[i].id, '"] input.quantity' ].join('')
        var unitsAvailableSelector = [ 'div[produceId="', produceInfo[i].id, '"] div.available' ].join('')

        var quantity = parseInt( $( quantitySelector ).val() );
        var originalUnitsAvailable = parseInt( $( unitsAvailableSelector ).attr('originalValue') );

        if( quantity > produceInfo[i].unitsRemaining ) {

            unableToFulfill = true;
            
            $( quantitySelector ).val( produceInfo[i].unitsRemaining );
            $( unitsAvailableSelector ).text( '0' ).attr( 'originalValue', produceInfo[i].unitsRemaining );
            updatePrice( produceInfo[i].id, $( quantitySelector ) );

        } else if( originalUnitsAvailable > produceInfo[i].unitsRemaining ) {

            $( unitsAvailableSelector ).text( produceInfo[i].unitsRemaining - quantity ).attr( 'originalValue', produceInfo[i].unitsRemaining );

        }
    }

    if( unableToFulfill ) {
    
        closeModalBox();

        $('#modalBoxTitle').text( 'This is unfortunate' );
        $('#modalBoxForm').append(
            makeEl('div').attr( { 'class': 'modalText' } )
                         .text( 'Someone else recently completed an order, and we are now unable to fill a portion of yours.  Please take a look at your updated order that reflects what we have available at the moment before checking out.  Thank you.' ) );
        
        $('#modalBoxContainer').show( 'slow', alignModalBox );

        info.checkoutButton.bind( 'click', { }, handleCheckoutClick );

    } else {

        var produceIds = [ ];
        var quantities = [ ];

        $( '.quantity' ).each(
            function( i, el ) {
               
                var el = $( el );

                if( parseInt( el.val() ) > 0 ) {
                    
                    produceIds.push( $( $( el.parent() ).parent() ).attr('produceId') );
                    quantities.push( el.val() );
                }
            }
        );

        var url = [ 'http://patchworkgardens.net/cgi-bin/makeOrder.py?customerId=',
                        encodeURIComponent( info.customer.deliveryInfo.customerId ),
                        '&produceIds=',
                        encodeURIComponent( produceIds.join('|') ),
                        '&quantityIds=',
                        encodeURIComponent( quantities.join('|') ),
                        '&address=',
                        encodeURIComponent( info.selectedAddress.text() ),
                        '&total=',
                        encodeURIComponent( info.currentTotal ),
                        '&emailAddress=',
                        encodeURIComponent( info.emailAddress ),
                        '&nextDelivery=',
                        encodeURIComponent( info.customer.deliveryInfo.nextDelivery ),
                        '&payment=',
                        $('input[name="payment"]:checked').val() ].join('');

        $.ajax( { url: url,
                  type: 'GET',
                  success: handleCheckoutResponse } );
            
    }
}

function handleCheckoutResponse( response ) {

    var responseObj = eval( '(' + response + ')' );

    if( responseObj.error ) {

        $( $('#modalBoxForm div.modalText')[0] ).text( 'There was an error processing your order.  Sorry for the inconvenience.  Please make the order again, or contact us by phone or email.' );

    } else {
        
        $( $('#modalBoxForm div.modalText')[0] ).text( 'Order complete!' );
    }

    setTimeout( function() { closeModalBox(); location.reload(); }, 5000 );
}

function alignModalBox() {

    var content = $('#modalBoxContent');
    var form = $('#modalBoxForm');

    content.css( { top: ( ( info.documentHeight - content.outerHeight( true ) ) / 2 ),
                   left: ( ( info.documentWidth - content.outerWidth( true ) ) / 2 ) } );
         
    if( ! info.modalWait ) {

        $( document ).bind( 'keydown', handleModalKeyPress );
        $( document ).bind( 'click', handleModalMouseClick );
    }
}

function handleModalKeyPress( e ) { if( e.keyCode == 27 ) { closeModalBox(); } }

function closeModalBox() {

    $('#modalBoxTitle').text('');

    $('#modalBoxForm').empty();

    $('#modalBoxContainer').hide();
    
    if( !info.modalWait ) {
        $(document).unbind( 'keydown', handleModalKeyPress );
        $(document).unbind( 'click', handleModalMouseClick );
    } else {
        info.modalWait = false;
    }
}

function handleModalMouseClick( e ) {

    if( ! ( isMouseOnElement( { x: e.pageX, y: e.pageY, el: $( '#modalBoxContent' ) } ) ) ) { closeModalBox(); }
}

function initializeModalBox() {

    $('body').append(
        makeEl('div').attr( { 'id': 'modalBoxContainer' } ).append(
            makeEl('div').attr( { 'class': 'modalBoxOverlay' } ),
            makeEl('div').attr( { 'id': 'modalBoxContent' } ).append(
                makeEl('div').attr( { 'id': 'modalBoxTitle' } ),
                makeEl('div').attr( { 'id': 'modalBoxForm' } ) ) ) );
}                                                                          


function isMouseOnElement( p ) {

    var elementOffset = p.el.offset();

    if( p.x < elementOffset.left || p.y < elementOffset.top ||
        p.x > ( elementOffset.left + p.el.outerWidth( true ) ) ||
        p.y > ( elementOffset.top + p.el.outerHeight( true ) ) ) {

        return false;

    } else { return true; }
}

function storeObjPosition( obj, location ) {
    
    location.myWidth = obj.outerWidth( true );
    location.myHeight = obj.outerHeight( true );
    location.myOffset = obj.offset();
    location.myPosition = obj.position();
    location.myBottom = location.myOffset.top + location.myHeight;
    location.myRight = location.myOffset.left + location.myWidth;

}

function makeEl( elementName ) { return $(document.createElement(elementName)); };

function setMouseToPointer() { document.body.style.cursor = 'pointer'; }
function setMouseToDefault() { document.body.style.cursor = 'default'; }

function makeModalTextInput( p ) {
    
    var input = makeEl('input').attr( { 'type': 'text', name: p.name, size: 75 } ).val( p.value );

    return makeEl('div').attr( { 'class': 'formRow' } ).append(
           makeEl('div').attr( { 'class': 'dialogueLabel' } ).text( p.text ),
                  makeEl('div').attr( { 'class': 'dialogueTextInput' } ).append( input ),
                     makeEl('div').attr( { 'class': 'clear' } ) );
}

function makeModalActionRow( p ) {
        
    var cancelElement = makeEl('div').attr( { 'class': 'dialogueButton twoOpt modalBoxCancel' } ).text('Cancel').click( closeModalBox );

    return makeEl('div').attr( { 'class': 'actionRow' } ).append(
        makeEl('div').attr( { 'class': 'dialogueButton twoOpt modalBoxSubmit' } ).text( p.submitText )
                    .bind( 'click', { }, p.onClick ),
        cancelElement,
        makeEl('div').attr( { 'class': 'clear' } ) );
}

function underlineText() { $(this).css( { 'text-decoration': 'underline' } ); }
function unUnderlineText() { $(this).css( { 'text-decoration': 'none' } ); }

function handleButtonClick() { $( this ).css( { 'background-color': '#74C365' } ); }
function handleButtonUnClick() { $( this ).css( { 'background-color': '#87CEEB' } ); }

$( window ).load( onPageLoad );
